package com.leetcode.array;

import java.util.HashMap;
import java.util.Map;

public class Leetcode567 {

    public boolean checkInclusion(String s1, String s2) {
        Map<Character, Integer> window = new HashMap<>();
        Map<Character, Integer> need = new HashMap<>();

        for (Character ch : s1.toCharArray()) {
            need.put(ch, need.getOrDefault(ch, 0) + 1);
        }

        int left = 0, right = 0;
        int valid = 0;

        while (right < s2.length()) {

            char cur = s2.charAt(right);
            right++;

            if (need.containsKey(cur)) {
                window.put(cur, window.getOrDefault(cur, 0) + 1);
                if (need.get(cur).intValue() == window.get(cur).intValue()) {
                    valid++;
                }
            }

            while (right - left >= s1.length()) {
                if (valid == need.size()) {
                    return true;
                }
                char leftCur = s2.charAt(left);
                left++;

                if (need.containsKey(leftCur)) {
                    if (need.get(leftCur).intValue() == window.get(leftCur).intValue()) {
                        valid--;
                    }
                    window.put(leftCur, window.get(leftCur) - 1);
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        String s1 = "ab", s2 = "eidboaoo";
        System.out.println(new Leetcode567().checkInclusion(s1, s2));
    }

}
